package com.dldata.devtools30.controller;

import com.alibaba.fastjson.JSON;
import com.dldata.devtools30.utils.StringUtil;
import com.dldata.devtools30.utils.dhtmlX.CSVWriter;
import com.dldata.devtools30.utils.dhtmlX.ExcelWriter;
import com.dldata.devtools30.utils.dhtmlX.ExcelWriterXss;
import com.dldata.devtools30.utils.dhtmlX.HTMLWriter;
import jxl.Workbook;
import jxl.write.WritableWorkbook;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Created by 呵呵 on 2017-12-13.
 */
@Controller
@RequestMapping(value = "/ExportController30")
public class Export30Controller {


    @RequestMapping(value = "html")
    public void html(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        String xml = req.getParameter("grid_xml");
        xml = URLDecoder.decode(xml, "UTF-8");
        String title = req.getParameter("title");
        title = URLDecoder.decode(title, "UTF-8");
        title =title==null?"":URLDecoder.decode(title, "UTF-8");
        HTMLWriter writer = new HTMLWriter();
        writer.generate(xml,title, resp);
    }


    @RequestMapping(value = "excel")
    public void excel(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String excelType = req.getParameter("excelType");
        String xml = req.getParameter("grid_xml");
        xml = URLDecoder.decode(xml, "UTF-8");
        int nodes =  DocumentHelper.parseText(xml).getRootElement().elements("row").size();
        if(nodes>60000||(!StringUtil.isEmptyOrLength0(excelType)&&excelType.equals("2007"))){
            excel2007(req,resp);
        }else{
            excel2003(req,resp);
        }
    }

    @RequestMapping(value = "excel2003")
    public void excel2003(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String xml = req.getParameter("grid_xml");
        xml = URLDecoder.decode(xml, "UTF-8");
        String title = req.getParameter("title");
        title =title==null?"":URLDecoder.decode(title, "UTF-8");
        ExcelWriter excelWriter = new ExcelWriter();
        excelWriter.generate(xml,title, resp.getOutputStream());
        excelWriter.outputExcel(resp,title);
    }
    @RequestMapping(value = "excel2007")
    public void excel2007(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String xml = req.getParameter("grid_xml");
        xml = URLDecoder.decode(xml, "UTF-8");
        String title = req.getParameter("title");
        title =title==null?"":URLDecoder.decode(title, "UTF-8");
        ExcelWriterXss excelWriter = new ExcelWriterXss();
        excelWriter.generate(xml,title);
        excelWriter.outputExcel(resp,title, resp.getOutputStream());
    }

    /**
     * [{id:id,name:name,gridxm:grid_xmll}]
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "excelV2")
    public void excelV2(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String json = req.getParameter("grid_xml");
        json = URLDecoder.decode(json, "UTF-8");
        String title = req.getParameter("title");
        title =title==null?"":URLDecoder.decode(title, "UTF-8");
        List<Map> mapList=JSON.parseArray(json,Map.class);

        WritableWorkbook wbb=null;
        for (int i = 0; i < mapList.size(); i++) {
            Map map = mapList.get(i);
            String grid_xml =URLDecoder.decode(map.get("gridxml").toString(), "UTF-8");
            if(i == 0){
                String titlesheet = map.get("name").toString();
                ExcelWriter excelWriter = new ExcelWriter();
                excelWriter.generate(grid_xml,titlesheet, resp.getOutputStream());
                wbb=excelWriter.getWb();
            }else {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ExcelWriter excelWriter = new ExcelWriter();
                excelWriter.generate(grid_xml,title,byteArrayOutputStream);
                excelWriter.close();
                Workbook workbook=
                        Workbook.getWorkbook(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
                String titlesheet = map.get("name").toString();
                wbb.importSheet(titlesheet, i,workbook.getSheet(0));
            }
        }
        resp.setContentType("application/vnd.ms-excel");
        resp.setCharacterEncoding("UTF-8");
        String downTitle = StringUtil.isEmptyOrLength0(title)?"grid.xls":title+".xls";
        downTitle= URLEncoder.encode(downTitle, "UTF-8");
        resp.setHeader("Content-Disposition", "attachment;filename="+downTitle);
        resp.setHeader("Cache-Control", "max-age=0");
        wbb.write();
        wbb.close();
    }


    @RequestMapping(value = "csv")
    public void csv(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        String xml = req.getParameter("grid_xml");
        xml = URLDecoder.decode(xml, "UTF-8");
        String title = req.getParameter("title");
        title = URLDecoder.decode(title, "UTF-8");
        title =title==null?"":URLDecoder.decode(title, "UTF-8");
        CSVWriter writer = new CSVWriter();
        writer.generate(xml,title, resp);
    }

    /**
     * [{"color":"",field:"ID",title:"ID","width":"100","align":"center","type":"str"}]
     *
     * [{"ID":"12345678"}]
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "easyuiexcel")
    public void easyuiexcel(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        Document document=DocumentHelper.createDocument();
        //创建根结点
        Element rootrows=document.addElement("rows");
        rootrows.add(DocumentHelper.createAttribute(rootrows,"profile","color"));

        Element headElement = rootrows.addElement("head");
        Element columnsElement = headElement.addElement("columns");

        Element columnsElement2 = headElement.addElement("columns");

        String header = req.getParameter("header");
        header = URLDecoder.decode(header, "UTF-8");
        List<Map> headerList=(List<Map>)JSON.parseArray(header, Map.class);
        for (int i = 0; i < headerList.size(); i++) {

            Map map = headerList.get(i);

            Element columnOneElement = columnsElement.addElement("column");
            columnOneElement.add(DocumentHelper.createAttribute(columnOneElement, "rowspan", "2"));
            columnOneElement.add(DocumentHelper.createAttribute(columnOneElement,"width", StringUtil.isEmptyOrLength0(map.get("width"))?"60":map.get("width").toString()));
            columnOneElement.add(DocumentHelper.createAttribute(columnOneElement, "align", StringUtil.isEmptyOrLength0(map.get("align")) ? "center" : map.get("align").toString()));
            columnOneElement.add(DocumentHelper.createAttribute(columnOneElement, "type", "ro"));
            columnOneElement.add(DocumentHelper.createAttribute(columnOneElement, "sort", StringUtil.isEmptyOrLength0(map.get("sort")) ? "str" : map.get("type").toString()));
            columnOneElement.add(DocumentHelper.createAttribute(columnOneElement, "color", StringUtil.isEmptyOrLength0(map.get("color")) ? "" : map.get("color").toString()));
            columnOneElement.add(DocumentHelper.createCDATA(StringUtil.isEmptyOrLength0(map.get("title")) ? " " : map.get("title").toString()));

            Element columnOneElement2 = columnsElement2.addElement("column");
            columnOneElement2.add(DocumentHelper.createCDATA(""));
        }

        String rows = req.getParameter("rows");
        rows = URLDecoder.decode(rows, "UTF-8");
        List<Map> rowsList=(List<Map>)JSON.parseArray(rows, Map.class);
        for (int i = 0; i < rowsList.size(); i++) {
            Map rowMap = rowsList.get(i);

            Element rowElement = rootrows.addElement("row");
            for (int j = 0; j < headerList.size(); j++) {
                Map mapHeader = headerList.get(j);
                Object valueCell= rowMap.get(mapHeader.get("field"));

                Element cellElement = rowElement.addElement("cell");
                cellElement.add(DocumentHelper.createCDATA(StringUtil.isEmptyOrLength0(valueCell)?"":valueCell.toString()));
            }
         }

        String title = req.getParameter("title");
        title =title==null?"":URLDecoder.decode(title, "UTF-8");
        ExcelWriter excelWriter = new ExcelWriter();
        excelWriter.generate(document.asXML(),title, resp.getOutputStream());
        excelWriter.outputExcel(resp,title);
    }
}
